import { Preferences } from '@kit.StorageKit';

class StorageUtil {
  private preferences: Preferences | null = null;

  private async getPreferences(): Promise<Preferences> {
    if (!this.preferences) {
      try {
        this.preferences = await Preferences.getPreferences(this.getAppContext(), 'app_data');
      } catch (error) {
        console.error('获取Preferences失败:', error);
        throw error;
      }
    }
    return this.preferences;
  }

  private getAppContext(): any {
    // 获取应用上下文
    return getContext();
  }

  async set(key: string, value: any): Promise<void> {
    const preferences = await this.getPreferences();
    try {
      await preferences.put(key, value);
      await preferences.flush();
    } catch (error) {
      console.error('存储数据失败:', error);
      throw error;
    }
  }

  async get(key: string): Promise<any> {
    const preferences = await this.getPreferences();
    try {
      return preferences.get(key, null);
    } catch (error) {
      console.error('读取数据失败:', error);
      return null;
    }
  }

  async remove(key: string): Promise<void> {
    const preferences = await this.getPreferences();
    try {
      await preferences.delete(key);
      await preferences.flush();
    } catch (error) {
      console.error('删除数据失败:', error);
      throw error;
    }
  }

  async clear(): Promise<void> {
    const preferences = await this.getPreferences();
    try {
      const keys = await preferences.getAllKeys();
      for (const key of keys) {
        await preferences.delete(key);
      }
      await preferences.flush();
    } catch (error) {
      console.error('清空数据失败:', error);
      throw error;
    }
  }
}

export default new StorageUtil();